package com.chl.tools;

import java.io.FileInputStream;
import java.io.IOException;

public class MagicNumberChecker {
	// PNG魔数
	private static final byte[] PNG_MAGIC_NUMBER = new byte[] { (byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };

	public static void main(String[] args) {
		String filePath = "C:\\Users\\006006\\Desktop\\111.pdf";
		// 这里替换为你的文件路径
		try {
			if (checkMagicNumber(filePath)) {
				System.out.println("该文件是PNG格式");
			} else {
				System.out.println("该文件不是PNG格式");
			}
		} catch (IOException e) {
			System.err.println("读取文件时发生错误: " + e.getMessage());
		}
	}

	private static boolean checkMagicNumber(String filePath) throws IOException {

		try (FileInputStream fis = new FileInputStream(filePath)) {
			byte[] fileMagicNumber = new byte[PNG_MAGIC_NUMBER.length];
			fis.read(fileMagicNumber);
			return compareMagicNumbers(fileMagicNumber, PNG_MAGIC_NUMBER);
		}
	}

	private static boolean compareMagicNumbers(byte[] fileMagic, byte[] pngMagic) {

		StringBuffer sb = new StringBuffer();
		for (byte b : fileMagic) {
			sb.append(String.format("%02X ", b));
		}
		System.out.println(sb.toString());

		if (fileMagic.length != pngMagic.length) {
			return false;
		}
		for (int i = 0; i < fileMagic.length; i++) {
			if (fileMagic[i] != pngMagic[i]) {
				return false;
			}
		}
		return true;
	}
}